/*
 * Register the given functions for the given signals
 *
 * Copyright 2023 Odin Kroeger.
 *
 * This file is part of suCGI.
 *
 * suCGI is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * suCGI is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700

#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>

#include "types.h"
#include "sigs.h"


int
sigs_trap(const size_t ntraps, const Trap *const traps, Trap *const old,
          const ErrorFn errh)
{
    assert(traps != NULL);

    int retval = 0;
    int fatalerr = 0;

    sigset_t allsignals;
    errno = 0;
    retval = sigfillset(&allsignals);
    if (retval != 0) {
        /* NOTREACHED */
        if (errh != NULL) {
            errh(EXIT_FAILURE, "%s:%d: sigfillset", __FILE__, __LINE__);
        }
        return retval;
    }

    sigset_t oldmask;
    errno = 0;
    retval = sigprocmask(SIG_SETMASK, &allsignals, &oldmask);
    if (retval != 0) {
        /* NOTREACHED */
        if (errh != NULL) {
            errh(EXIT_FAILURE, "%s:%d: sigprocmask", __FILE__, __LINE__);
        }
        return retval;
    }

    for (size_t i = 0; i < ntraps; ++i) {
        assert(traps[i].action != NULL);

        const int signal = traps[i].signal;
        const struct sigaction *const action = traps[i].action;
        struct sigaction *ptr = NULL;

        errno = 0;
        retval = sigaction(signal, action, ptr);
        if (retval != 0) {
            fatalerr = errno;
            break;
        }

        if (old != NULL) {
            old[i] = (Trap) {
                .action = ptr,
                .signal = signal
            };
        }
    }

    errno = 0;
    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) != 0) {
        /* NOTREACHED */
        if (retval == 0) {
            if (errh != NULL) {
                errh(EXIT_FAILURE, "%s:%d: sigprocmask", __FILE__, __LINE__);
            }
            return -1;
        }
    }

    errno = fatalerr;
    if (retval != 0 && errh != NULL) {
        /* NOTREACHED */
        errh(EXIT_FAILURE, "%s:%d: sigaction", __FILE__, __LINE__);
    }

    return retval;
}
